package com.youxin.foundation.utils.thread;

import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import com.youxin.foundation.utils.locks.LockObject;

/**
 * 定时任务接口
 * @author yingde.cao
 *
 */
public class ScheduleThreadPool {
	
	private  ScheduledThreadPoolExecutor executorService;	
	
	public ScheduleThreadPool()
	{
		this(BaseThreadPool.CORE_POOL_SIZE);
	}
	
	public ScheduleThreadPool(int corePoolSize) {
		executorService=new ScheduledThreadPoolExecutor(corePoolSize, new 
				BaseThreadFactory(ScheduleThreadPool.class.getName()));
	}
	
	public ScheduledThreadPoolExecutor getExecutorService() {
		return executorService;
	}

	private static ScheduleThreadPool threadPool;
	/**
	 * 单例
	 * 
	 * @param corePoolSize
	 *            线程池核心运行数
	 * @return ScheduleThreadPool
	 */
	public static ScheduleThreadPool instance(int corePoolSize) {
		if (threadPool == null) {
			LockObject.lock(() -> {
				if (threadPool != null) {
					return;
				}
				threadPool = new ScheduleThreadPool(corePoolSize);
			});
		}
		return threadPool;
	}

	
	
	/**
	 * 添加定时任务 运行一次的定时任务
	 * @param runnable 任务接口
	 * @param milliseconds 毫秒
	 */
	public static void schedule(Runnable runnable,long delay)
	{
		if (threadPool == null) {
			instance(BaseThreadPool.CORE_POOL_SIZE);
		}
		try {
			threadPool.getExecutorService().schedule(runnable, delay, TimeUnit.MILLISECONDS);
		} finally {
			// TODO: handle finally clause
		}
	}
	/**
	 * 定时任务,上一个任务结束后延迟多少秒,重新启动任务
	 * @param runnable
	 * @param milliseconds 周期性
	 * @param delay 初始延迟
	 */
	public static void scheduleWithFixedDelay(Runnable runnable,long milliseconds,long delay)
	{
		if (threadPool == null) {
			instance(BaseThreadPool.CORE_POOL_SIZE);
		}
		try {
			threadPool.getExecutorService().scheduleWithFixedDelay(runnable,delay, milliseconds, TimeUnit.MILLISECONDS);
		} finally {
			// TODO: handle finally clause
		}
	}
	/**
	 * 定时任务,上一个任务开启,延迟多少秒重新启动任务
	 * @param runnable
	 * @param milliseconds 周期性
	 * @param delay  初始延迟
	 */
	public static void scheduleAtFixedRate(Runnable runnable,long milliseconds,long delay)
	{
		if (threadPool == null) {
			instance(BaseThreadPool.CORE_POOL_SIZE);
		}
		
		try {
			threadPool.getExecutorService().scheduleAtFixedRate(runnable,delay, milliseconds, TimeUnit.MILLISECONDS);
		} finally {
		}
	}
	
	public  void shutdown()
	{
		try {
			if(executorService!=null)
			{
				executorService.shutdown();
			}
		} catch (Exception e) {
			// TODO: handle exception
		}		
	}
	
	public static boolean stop()
	{
		try {
			if(threadPool!=null)
			{
				threadPool.shutdown();
				return true;
			}
		} catch (Exception e) {
			return true;
		}		
		return false;
	}
	
}
